import React, { useState } from 'react';

const ImageQuestion = ({ question, onAnswer, onNext }) => {
  const [userAnswer, setUserAnswer] = useState('');
  const [isCorrect, setIsCorrect] = useState(null);
  const [showHint, setShowHint] = useState(false);
  const [showExplanation, setShowExplanation] = useState(false);
  const [imageError, setImageError] = useState(false);
  const [imageLoading, setImageLoading] = useState(true);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!userAnswer.trim()) return;

    const correct = question.correctAnswers.some(answer => 
      userAnswer.trim().toLowerCase() === answer.toLowerCase()
    );
    
    setIsCorrect(correct);
    onAnswer(correct, userAnswer, showHint);
    setShowExplanation(true);
  };

  const handleNext = () => {
    setUserAnswer('');
    setIsCorrect(null);
    setShowHint(false);
    setShowExplanation(false);
    setImageError(false);
    setImageLoading(true);
    onNext();
  };

  const handleImageLoad = () => {
    setImageLoading(false);
  };

  const handleImageError = () => {
    setImageError(true);
    setImageLoading(false);
  };

  const getImageUrl = () => {
    if (imageError) {
      // 备用图片
      return `https://picsum.photos/400/300?random=${question.id + 100}`;
    }
    return question.imageUrl;
  };

  return (
    <div className="card">
      <h2>根据图片或语法填入日语</h2>
      
      <div style={{ marginBottom: '20px' }}>
        <div style={{ position: 'relative', marginBottom: '20px' }}>
          {imageLoading && (
            <div style={{ 
              width: '400px', 
              height: '300px', 
              backgroundColor: '#f0f0f0', 
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'center',
              borderRadius: '8px'
            }}>
              图片加载中...
            </div>
          )}
          <img
            src={getImageUrl()}
            alt="题目图片"
            style={{ 
              width: '400px', 
              height: '300px', 
              objectFit: 'cover', 
              borderRadius: '8px',
              display: imageLoading ? 'none' : 'block'
            }}
            onLoad={handleImageLoad}
            onError={handleImageError}
          />
        </div>
        
        <div style={{ 
          backgroundColor: '#f8f9fa', 
          padding: '15px', 
          borderRadius: '8px',
          marginBottom: '20px'
        }}>
          <p style={{ margin: '0', fontSize: '16px', lineHeight: '1.6' }}>
            <strong>题目：</strong>{question.sentence}
          </p>
        </div>
      </div>

      <form onSubmit={handleSubmit}>
        <div style={{ marginBottom: '20px' }}>
          <label htmlFor="answer" style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
            请输入答案：
          </label>
          <input
            type="text"
            id="answer"
            value={userAnswer}
            onChange={(e) => setUserAnswer(e.target.value)}
            placeholder="请输入日语单词或短语"
            style={{
              width: '100%',
              padding: '12px',
              fontSize: '16px',
              border: '2px solid #ddd',
              borderRadius: '8px',
              boxSizing: 'border-box'
            }}
            disabled={isCorrect !== null}
          />
        </div>

        <div style={{ display: 'flex', gap: '10px', marginBottom: '20px' }}>
          <button
            type="submit"
            className="btn"
            disabled={!userAnswer.trim() || isCorrect !== null}
            style={{ flex: 1 }}
          >
            提交答案
          </button>
          
          {!showHint && (
            <button
              type="button"
              className="btn btn-secondary"
              onClick={() => setShowHint(true)}
              disabled={isCorrect !== null}
            >
              显示提示
            </button>
          )}
        </div>
      </form>

      {showHint && (
        <div style={{ 
          backgroundColor: '#fff3cd', 
          padding: '15px', 
          borderRadius: '8px',
          marginBottom: '20px',
          border: '1px solid #ffeaa7'
        }}>
          <p style={{ margin: '0', color: '#856404' }}>
            <strong>💡 提示：</strong>{question.hint}
          </p>
        </div>
      )}

      {isCorrect !== null && (
        <div style={{ 
          backgroundColor: isCorrect ? '#d4edda' : '#f8d7da', 
          padding: '15px', 
          borderRadius: '8px',
          marginBottom: '20px',
          border: `1px solid ${isCorrect ? '#c3e6cb' : '#f5c6cb'}`
        }}>
          <p style={{ 
            margin: '0', 
            color: isCorrect ? '#155724' : '#721c24',
            fontWeight: 'bold'
          }}>
            {isCorrect ? '✅ 回答正确！' : '❌ 回答错误'}
          </p>
          {!isCorrect && (
            <p style={{ margin: '10px 0 0 0', color: '#721c24' }}>
              <strong>正确答案：</strong>{question.correctAnswers.join(' 或 ')}
            </p>
          )}
        </div>
      )}

      {showExplanation && (
        <div style={{ 
          backgroundColor: '#e7f3ff', 
          padding: '15px', 
          borderRadius: '8px',
          marginBottom: '20px',
          border: '1px solid #b3d9ff'
        }}>
          <p style={{ margin: '0', color: '#004085' }}>
            <strong>📚 解析：</strong>{question.explanation}
          </p>
        </div>
      )}

      {isCorrect !== null && (
        <button className="btn" onClick={handleNext} style={{ width: '100%' }}>
          {isCorrect ? '下一题' : '继续'}
        </button>
      )}
    </div>
  );
};

export default ImageQuestion; 